
require 'raklur/rdebug'

module Raklur
	#
	#
	#
	module Plugin ; end

	#
	#
	#
	class AccountFactoryError < SyntaxError ; end


	#
	#
	#
	class AccountFactory
		@@debug = true

		def self.create name, data
			raise AccountFactoryError, "type not specified" unless data.has_key? "type"
			plugin_dir = "%s/plugins/%s" % [ File.dirname(__FILE__), data["type"] ]
			plugin_account = "%s/account.rb" % plugin_dir
			plugin_stream = "%s/stream.rb" % plugin_dir

			rdebug "testing plugin directory %s" % plugin_dir if @@debug		
			unless File.exist? plugin_dir and File.directory? plugin_dir then
				raise AccountFactoryError, "unable to find plugin for type=%s" % data['type']
			end
			unless File.exists? plugin_account and File
				raise AccountFactoryError, "account.rb not found in #{plugin_dir}"
			end
			unless File.exists? plugin_stream and File
				raise AccountFactoryError, "stream.rb not found in #{plugin_dir}"
			end

			begin
				require plugin_account
				require plugin_stream
				#FIXME: catch loaderrors
			rescue LoadError => e
				raise e
			end

			# search plugin for current data[type]
			Raklur::Plugin.constants.each do |symbol|
				if symbol =~ /#{data["type"]}/i then
					plugin_mod = Raklur::Plugin.const_get(symbol)
					account = plugin_mod.const_get("Account").new name, data
					account.validate_config
					return account
				end
			end

			# FIXME: test if all required parameters are set for given plugin
			# FIXME: return a (configured) account
			return nil
		end

		private

		#
		#
		#
		def initialize
		end
	end
end
